<!-- 事件日志 -->
<template>
  <!-- <div class="dashboard-editor-container"> -->
  <div style="display:flex;justify-content:space-between;">
    <partitionTree :nodeData="nodeData" :expandArray="expandArray" :addTemplate="false" :defaultExpandAll="false" dialogName="DeviceRealPerfStatus"
      @handleNodeClick="handleNodeClick" ref="partitionTree" @toggleVisibility="toggleVisibility"
      minHeight="calc(100vh - 142px)">
    </partitionTree>
    <div :style="{ width: containerWidth }" class="box"
      style="background:#fff;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
      <el-row style="background: #fff;">
        <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset"></connsearch>
        <div class="tabclick">
          <div class="tabitem" @click="handleClick()">
            <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
          </div>
        </div>
        <el-row>
          <el-tabs type="border-card" v-if="tab" style="margin-top:16px;" @tab-click="tabClick">
            <el-tab-pane label="按分布比例资产统计分析" lazy>
              <el-row :gutter="20">
                <el-col :xs="24" :sm="24" :lg="24">
                  <piechart :chartData="pie1Data" @pieclick="echartsClick" title="按分布比例资产统计分析" />
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-row>
        <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }"
          style="padding-right: 8px;margin:16px 0;">
          <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
            <el-table-column label="序号" width="60" type="index"
              :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
            <el-table-column label="部门" show-overflow-tooltip prop="Department" width="120px"></el-table-column>
            <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" width="160px"></el-table-column>
            <el-table-column label="使用者" show-overflow-tooltip prop="UserName" width="120px"></el-table-column>
            <el-table-column label="采集时间" show-overflow-tooltip prop="TransTime" width="160"></el-table-column>
            <el-table-column label="扩展盘使用率" show-overflow-tooltip prop="Percent">
              <template slot-scope="{row}">
                <div v-if="row.Total == '0.00GB'">-</div>
                <div v-else class="coldiv hasprogress"><el-progress style="width:80%" :stroke-width="10"
                    :percentage="row.Percent"></el-progress>{{ row.Used }} / {{ row.Total }}</div>
              </template>
            </el-table-column>
            <!-- <el-table-column label="操作" show-overflow-tooltip width="120px"  fixed="right" >
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="changeModer(scope.row)">最近曲线</el-button>
            </template>
          </el-table-column> -->
          </el-table>
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page=pageNum
            :page-size=pageSize background layout="total, prev, pager, sizes, next, jumper" :total="total">
          </el-pagination>
        </el-col>
        <el-dialog :close-on-click-modal="false" :close-on-press-escape=false title="最近曲线" :visible.sync="logDialog"
          v-el-drag-dialog width="800px">
          <linechart :chartData="lineData"></linechart>
          <span slot="footer" class="dialog-footer">
            <el-button type="info" @click="logDialog = false">关 闭</el-button>
          </span>
        </el-dialog>
      </el-row>
    </div>
  </div>
  <!-- </div> -->
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import linechart from "./components/linechart.vue"
import piechart from "./components/piechart.vue";
import { parseTime, GetDeviceTree2 } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js"
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import partitionTree from "@/components/partitionTree";
export default {
  directives: { elDragDialog },
  components: { connsearch, piechart, linechart, partitionTree },
  data() {
    let that = this
    return {
      activeName: "",
      tabTitle: '按分布比例资产统计分析',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      barchartData: { xAxis: [], series: [] },
      pie1Data: [],
      nodeData: [],
      expandArray: [],
      containerWidth: 'calc(100% - 275px)',
      lineData: {},
      tableData: [],
      searchform: {},
      options: {},
      nodeobj: {},
      searchobj: {},
      echartsobj: {},
      logDialog: false,
      formOptions: [
        {
          col: 8,
          hidden: false,
          label: "日期", // label文字
          prop: "timeRange", // 字段名
          initValue: [], // 字段初始值,
          element: "el-date-picker", // 指定elementui组件
          type: "", // 日期选择类型,
          events: {
            input(val) {
              that.searchform.timeRange = val
            },
          },
        },
        {
          col: 4,
          label: "最小使用率",
          prop: "MinPercent",
          element: "el-select",
          initValue: 0,
          placeholder: "请选择使用率",
          options: [
            { label: '0%', value: 0 },
            { label: '10%', value: 10 },
            { label: '20%', value: 20 },
            { label: '30%', value: 30 },
            { label: '40%', value: 40 },
            { label: '50%', value: 50 },
            { label: '60%', value: 60 },
            { label: '70%', value: 70 },
            { label: '80%', value: 80 },
            { label: '90%', value: 90 },
          ],
          events: {
            input(val) {
              that.searchform.MinPercent = val
            },
          },
        },
        {
          col: 4,
          label: "最大使用率",
          prop: "MaxPercent",
          element: "el-select",
          initValue: 100,
          placeholder: "请选择使用率",
          options: [
            { label: '10%', value: 10 },
            { label: '20%', value: 20 },
            { label: '30%', value: 30 },
            { label: '40%', value: 40 },
            { label: '50%', value: 50 },
            { label: '60%', value: 60 },
            { label: '70%', value: 70 },
            { label: '80%', value: 80 },
            { label: '90%', value: 90 },
            { label: '100%', value: 100 },
          ],
          events: {
            input(val) {
              that.searchform.MaxPercent = val
            },
          },
        },
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = (Cookies.get('Zhuoguan_DefaultPageLength') || 10) * 1;

    let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
    let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
    let arr = [parseTime(startTime), '']
    this.formOptions.map(item => {
      if (item.label === '日期') {
        item.initValue = arr
      }
    })
    this.$set(this.searchform, 'timeRange', arr)
    this.$set(this.searchform, 'MinPercent', 0)
    this.$set(this.searchform, 'MaxPercent', 100)
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.initData()
  },
  methods: {
    async initData(searchobj = {}) {
      try {
        const {DeviceTree} = await GetDeviceTree2('DeviceRealPerfStatus', {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          MinPercent: this.searchform.MinPercent,
          MaxPercent: this.searchform.MaxPercent,
          PerfType: 4, 
          ...searchobj})
        this.nodeData = DeviceTree
        this.expandArray = [DeviceTree?.[0]?.Name]
      } catch (error) {
        this.$message.error('加载设备树数据失败');
      }
    },
    handleNodeClick(nodeData) {
      this.pageNum = 1
      this.nodeobj = { DepartmentID: nodeData.data.isDevice ? nodeData.data.DepartmentID : nodeData.data.ID, DeviceUUID: nodeData.data.isDevice ? nodeData.data.DeviceUUID : '' }
      this.echartsobj = {}
      this.getData({ ...this.searchobj, ...this.nodeobj })
    },
    toggleVisibility(isHidden) {
      if (isHidden)
        this.containerWidth = '100%';
      else
        this.containerWidth = 'calc(100% - 275px)';
    },
    // 获取所有数据
    getData(searchobj = {}) {
      this.GetEventLog(searchobj)
      switch (this.tabTitle) {
        case '按分布比例资产统计分析':
          this.GetDeviceRealPerfStatusSumGroupByDevice(searchobj)
          break;
      }
    },
    echartsClick(val, title) {
      this.pageNum = 1
      if (title === '按分布比例资产统计分析') {
        let percent = val.split('%')[0] * 1
        this.echartsobj = { MinPercent: percent, MaxPercent: percent + 10 }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      } 
    },
    tabClick(row) {
      this.tabTitle = row.label
      switch (row.label) {
        case '按分布比例资产统计分析':
          this.GetDeviceRealPerfStatusSumGroupByDevice({ ...this.searchobj, ...this.nodeobj})
          break;
      }
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}) {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          MinPercent: this.searchform.MinPercent,
          MaxPercent: this.searchform.MaxPercent,
          PerfType: 4,
          ...searchobj
        }
      }
      const res = await connrequest('GetDeviceRealPerfStatus', data)
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        item.Used = (item.Used / 1000).toFixed(2) + 'GB'
        item.Total = (item.Total / 1000).toFixed(2) + 'GB'
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    // 按分布比例资产统计分析
    async GetDeviceRealPerfStatusSumGroupByDevice(searchobj = {}) {
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          MinPercent: this.searchform.MinPercent,
          MaxPercent: this.searchform.MaxPercent,
          PerfType: 4,
          ...searchobj
        }
      }
      const res = await connrequest('GetDeviceRealPerfStatusSumGroupByDevice', data);
      const arr = (res.Data || []).filter(item => item.Count > 0).map(item => ({
        name: `${item.ClassID - 10}% ~ ${item.ClassID}%`,
        value: item.Count
      }));
      this.pie1Data = arr;
    },
    
    async changeModer(row) {
      const data = {
        Filter: {
          DeviceUUID: row.DeviceUUID,
          PerfType: 4,
        }
      }
      const res = await connrequest('GetDeviceHistoryPerfStatus', data)
      let downByte = []
      let time = []
      res.Data.map(item => {
        downByte.push(item.Percent)
        time.push(parseTime(item.TransTime))
      })
      this.lineData = { time, downByte }
      this.logDialog = true
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = { ...val }
      this.searchform = { ...val }
      if (this.searchform.timeRange) {
        this.searchobj = { ...this.searchobj, StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData({ ...this.echartsobj, ...this.searchobj, ...this.nodeobj })
      this.initData({...this.searchobj})
    },
    // 重置
    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
      let arr = [parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map(item => {
        if (item.label === "日期") {
          item.initValue = arr
        } else if (item.label === "最小使用率") {
          item.initValue = 0
        } else if (item.label === "最大使用率") {
          item.initValue = 100
        } else {
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.echartsobj = {}
      this.searchobj = {}
      this.nodeobj = {}
      this.$set(this.searchform, 'timeRange', arr)
      this.$set(this.searchform, 'MinPercent', 0)
      this.$set(this.searchform, 'MaxPercent', 100)
      this.$refs.connsearch.addInitValue()
      this.getData()
      this.initData()
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.GetEventLog({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
    },
    handleClick() {
      this.tab = !this.tab
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
</style>